<?php

	namespace org\tekuna\plugin\simplesecurity\action;
	
	use org\tekuna\framework\request\Request;
	use org\tekuna\framework\request\RequestException;
	use org\tekuna\framework\filter\FilterException;
	use org\tekuna\framework\filter\data\ValidatingFilter;
	use org\tekuna\framework\filter\data\AlphanumericCharsFilter;
	use org\tekuna\framework\filter\data\PrintableCharsFilter;
	use org\tekuna\framework\action\ActionEvent;
	use org\tekuna\framework\action\AbstractAction;
	use org\tekuna\framework\response\cli\CliErrorResponse;
	
	use org\tekuna\plugin\simplesecurity\SecurityManager;

	
	class GeneratePasswordAction extends AbstractAction {
		
		private $objSecurityManager;
		
		public function execute(ActionEvent $objActionEvent, Request $objRequest) {

			try {
				
				// setting a quite restrictive filter for the login (3rd arg)
				$objRequest -> setArgumentFilter(3, new ValidatingFilter(new AlphanumericCharsFilter()));
				
				// setting a quite open filter for the password (4th arg)
				$objRequest -> setArgumentFilter(4, new ValidatingFilter(new PrintableCharsFilter()));
				
				// get the parameters; values are already filtered here!
				$sLogin = $objRequest -> getArgument(3);
				$sPassword = $objRequest -> getArgument(4);
				
				// perform the password encryption
				$sEncryptedPassword = $this -> objSecurityManager -> encryptPassword($sLogin, $sPassword);
				
				// print result
				echo "encrypted password: $sEncryptedPassword\n";
				echo "You can use the following line for the application.xml:\n";
				echo "<security:user login=\"$sLogin\" encrypted-password=\"$sEncryptedPassword\" name=\"\" roles=\"\" />\n";
			}
			catch (FilterException $objException) {
				
				// the ValidatingFilter throws the FilterException if
				// the data was changed by the inner filter
				$sErrorMessage = "The provided parameters were not valid.\n";
				$sErrorMessage .= "  - the login may contain only alphanumeric characters (a-z, A-Z, 0-9)\n";
				$sErrorMessage .= "  - the password may not contain any control characters\n";
				
				return new CliErrorResponse($sErrorMessage);
			}
			catch (RequestException $objException) {
				
				// the CliRequest throws the RequestException if a requested
				// argument was not available
				$sErrorMessage = "Usage:\n";
				$sErrorMessage .= "php index.php simple-security generate-password [login] [password]\n";
				
				return new CliErrorResponse($sErrorMessage);
			}
		}
		
		
		/**
		 * Here the Security Manager gets injected from the context
		 * 
		 * @param SecurityManager $objSecurityManager
		 */
		public function setSimpleSecurityManager(SecurityManager $objSecurityManager) {
			
			$this -> objSecurityManager = $objSecurityManager;
		}
	}